/**
 *
 * @author 朱雀
 */
Ext.define('SvgEditor.canvas.Widget', {
	extend: 'Ext.container.Container',
	canvas: null,
	width: 46,
	defaults: {
		columnWidth: .5
	},
	initComponent: function() {
		var me = this;
		me.initQuickSvg(me);
		me.items = me.quickSvg;
		me.callParent();
	},
	initQuickSvg: function(me) {
		me.quickSvg = [
			Ext.create('Ext.button.Button', {
				name: 'UserTask',
				iconCls: 'User',
//				text: '圆形',
				handler: me.newModel,
				canvas: me.canvas
			}),
			Ext.create('Ext.button.Button', {
				name: 'circle',
				iconCls: 'Circle',
//				text: '圆形',
				handler: me.newModel,
				canvas: me.canvas
			}),
			Ext.create('Ext.button.Button', {
				name: 'rect',
				iconCls: 'Rect',
//				text: '矩形',
				handler: me.newModel,
				canvas: me.canvas
			}),
			Ext.create('Ext.button.Button', {
				name: 'ellipse',
				iconCls: 'Ellipse',
//				text: '椭圆',
				handler: me.newModel,
				canvas: me.canvas
			}),
			Ext.create('Ext.button.Button', {
				name: 'path',
				iconCls: 'Path',
//				text: '箭头',
				handler: me.newModel,
				canvas: me.canvas
			})
		];
	},
	newModel: function() {
		var type = this.name, canvas = this.canvas, origin = canvas.origin, modelConfig,
				node = canvas.treeStore.getNodeById(type);
		if (node) {
			modelConfig = node.data;
		} else {
			modelConfig = {
				type: type
			};
		}
		if (type === 'image') {
			modelConfig.view = this.view;
		}
		if (this.attrs) {
			modelConfig.attrs = this.attrs;
		}
		if (canvas.selected.length === 1 && type !== 'path') {
			var selectedModel = canvas.selected[0], x, y;
			if (type === 'circle' || type === 'ellipse') {
				x = selectedModel.coreX + 150;
				y = selectedModel.coreY + origin.offsetY;
			} else {
				x = selectedModel.coreX + 150;
				y = selectedModel.coreY + origin.offsetY - 40;
			}
			x += origin.offsetX;
			var newModel = canvas.addModel(canvas, modelConfig, x, y);
			canvas.link(canvas, selectedModel, newModel);
		} else if (type !== 'path') {
			canvas.addModel(canvas, modelConfig);
		}
	},
	afterFirstLayout: function() {
		var me = this, canvas = me.canvas;
		me.callParent();
		new Ext.dd.DragSource(me.items.items[4].getId(), {
			group: 'pathDD',
			afterDragDrop: function(target, e, id) {
				var canvas = Ext.getCmp(id);
				canvas.link(canvas, canvas.selected[0], canvas.target);
			}
		});
		var target = new Ext.dd.DDTarget(canvas.getId(), 'pathDD');
	}
});